package auth

import (
	"github.com/medivhzhan/weapp"
	log "github.com/sirupsen/logrus"
	"gitee.com/xiaofengfeng123/srv-paper-tape/config"
	"gitee.com/xiaofengfeng123/srv-paper-tape/database"
	"gitee.com/xiaofengfeng123/srv-paper-tape/utils"
	"time"
)

type Service interface {
	Login(code,rawData, encryptedData, signature, iv string)(user *database.User,err error)
	GetOpenid(code string)(*database.User,error)
}

type UserInfo struct {
	Uname          string        `json:"uname"`              //用户微信名
	Uavatar        string        `json:"uavatar"`            //用户头像
	Ugender        int           `json:"ugender"`            //用户性别
	Uage           int           `json:"uage"`               //用户年龄
	Uaddress       string        `json:"uaddress"`           //用户地址
}

type authServer struct {
}

func login(code string)(weapp.LoginResponse,error){
	return weapp.Login(config.AppID, config.Aecret, code)

}

func ( sv authServer)Login(code,rawData, encryptedData, signature, iv string)(user *database.User,err error){
	res,err := login(code)
	if err !=nil{
		log.Errorf("login error: %s",err.Error())
		return
	}
	log.Info("login ok: ","openid:",res.OpenID," unionid:",res.UnionID," key",res.SessionKey)

	return decryptUserInfo(rawData,encryptedData,signature,iv,res.SessionKey)
}

func (sv authServer)GetOpenid(code string)(*database.User,error){
	res,err := login(code)
	if err !=nil{
		log.Errorf("login error: %s",err.Error())
		return nil,err
	}
	log.Info("login ok: ","openid:",res.OpenID," unionid:",res.UnionID," key",res.SessionKey)
	u := new(database.User)

	uu,b := database.UserByUid(res.OpenID)
	if b{
		return uu,nil
	}

	u.Id = utils.GenUUID()
	u.Uid = res.OpenID
	u.CreateTime = time.Now()
	u.UpdateTime = u.CreateTime
	u.UnionId = res.UnionID

	_,err = database.Engine.Insert(u)
	if err !=nil{
		log.Errorf("insert user error: %s",err.Error())
		return nil,err
	}
	return u,nil
}

func decryptUserInfo(rawData, encryptedData, signature, iv, ssk string)(*database.User,error){

	user,err := weapp.DecryptUserInfo(rawData, encryptedData, signature, iv, ssk)
	if err !=nil{
		log.Errorf("get user info error: %s", err.Error())
		return nil,err
	}

	u,_ := database.UserByUid(user.OpenID)
	if u.Uavatar != ""{
		return u,nil
	}

	u.Uname = user.Nickname
	u.Uavatar = user.Avatar
	u.Uaddress = user.Province + "-" +user.City
	u.Ugender = user.Gender
	u.UpdateTime = time.Now()
	u.UnionId = user.UnionID

	_,err = database.Engine.ID(u.Id).Update(u)
	if err !=nil{
		log.Errorf("insert user error: %s",err.Error())
		return nil,err
	}
	return u,nil
}

func NewService()Service{
	return new(authServer)
}
